package com.zfei.gfb.device;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * hash缓存
 *
 * @author wangxb
 */
public class HashCache {

    private final StringRedisTemplate redis;

    public HashCache(RedisConnectionFactory factory) {
        this.redis = new StringRedisTemplate(factory);
    }

    public StringRedisTemplate getRedis() {
        return redis;
    }


    public void insertHash(String key, String field, Object val, Duration timeout) {
        this.redis.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection conn = (StringRedisConnection) connection;
            conn.hSet(key, field, val.toString());
            conn.expire(key, timeout.getSeconds());
            return null;
        });
        this.redis.opsForHash().put(key, field, val.toString());
    }

    public Map<Object, Object> listHash(String key) {
        return this.redis.opsForHash().entries(key);
    }

    public void deleteHash(String key, List<String> expireKeys) {
        this.redis.opsForHash().delete(key, expireKeys.toArray(new Object[0]));
    }

    public Object getHash(String key, String field) {
        return this.redis.opsForHash().get(key, field);
    }

    public List<Object> multiGet(String key, List<String> fields) {
        return this.redis.opsForHash().multiGet(key, new ArrayList<>(fields));
    }

    public boolean exist(String name) {
        Boolean exist = this.redis.hasKey(name);
        return exist != null && exist;
    }
}
